<template>
  <div class="card-list">
    <div v-for="(item,index) in UserData" :key="index">
        <Data :title="item.title" :num="item.num"></Data>
    </div>
  </div>

  <div class="shaixuan">
    <div class="shaixuan-content">
        <el-input
              v-model="searchKeyword"
              placeholder="请输入搜索关键词"
              style="width:200px;"
              clearable
              :prefix-icon="Search"
            >
        </el-input>
        <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @clear="handleClear"
            />
            <el-button
              type="primary"
              @click="handleSearch"
            >
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button
              type="success"
              @click="handleAdd"
            >
              <el-icon><Plus /></el-icon>新增
            </el-button>
    </div>
  </div>

  <div class="table">
    <el-table :data="tableData" border stripe>
        <el-table-column prop="user_id" label="用户ID" width="100" />
              <el-table-column prop="user_avatur" label="头像" width="80">
                <template #default="scope">
                  <img
                    :src="scope.row.user_avatur"
                    class="avatur"
                  />
                </template>
        </el-table-column>
        <el-table-column prop="user_nickname" label="昵称" />
        <el-table-column prop="user_createtime" label="注册时间" >
            <template #default="scope">
              <span>{{ formatTimestamp(scope.row.user_createtime) }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="is_delete" label="状态" >
            <template #default="scope">
              <span>{{ scope.row.is_delete==0?'正常':'封禁' }}</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleEdit(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    type="info"
                    size="small"
                    @click="handleView(scope.row)"
                    >查看</el-button
                  >
                </template>
        </el-table-column>
    </el-table>
    <div class="pagination">
        <el-pagination
              v-model:current-page="PageNo"
              v-model:page-size="PageSize"
              :total="total"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageNoChange"
            />
    </div>
  </div>
  <el-dialog v-model="detailshow" title="详情" width="300px">
    <div class="detail-item">
        <span>用户ID:</span>
        <span>{{ detail.user_id }}</span>
    </div>
    <div class="detail-item">
        <span>注册邮箱:</span>
        <span>{{ detail.user_mail }}</span>
    </div>
    <div class="detail-item">
        <span>头像:</span>
        <el-image :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[detail.user_avatur]" show-progress :initial-index="0" class="avatur" :src="detail.user_avatur"></el-image>
    </div>
    <div class="detail-item">
        <span>昵称:</span>
        <span>{{ detail.user_nickname }}</span>
    </div>
    <div class="detail-item">
        <span>注册时间:</span>
        <span>{{ formatTimestamp(detail.user_createtime) }}</span>
    </div>
    <div class="detail-item">
        <span>粉丝数:</span>
        <span>{{ detail.user_fans }}</span>
    </div>
    <div class="detail-item">
        <span>关注数:</span>
        <span>{{ detail.user_idols }}</span>
    </div>
    <div class="detail-item">
        <span>状态:</span>
        <span>{{ detail.is_delete==0?'正常':'封禁' }}</span>
    </div>
    <div class="detail-item">
        <span>背景图:</span>
        <el-image :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[detail.user_background]" show-progress :initial-index="0" class="background" :src="detail.user_background"></el-image>
    </div>
  </el-dialog>
  <el-dialog v-model="editshow" @close="clearedit" title="编辑" width="300px">
    <div class="edit-item">
        <span>头像:</span>
        <el-image :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[edit.user_avatur]" show-progress :initial-index="0" class="avatur" :src="edit.user_avatur"></el-image>
        <el-button
            type="primary"
            size="small"
            @click="avaturinput.click()"
            >上传</el-button
          >
        <input type="file" accept="image/*" @change="handleAvaturChange" ref="avaturinput" style="display: none;" />
    </div>
    <div class="edit-item">
        <span>昵称:</span>
        <el-input style="width: 200px;" v-model="edit.user_nickname"/>
    </div>
    <div class="edit-item">
        <span>状态:</span>
        <el-select style="width: 200px;"
            v-model="edit.is_delete"
          >
            <el-option
              label="正常"
              :value="0"
            />
            <el-option
              label="封禁"
              :value="1"
            />
          </el-select>
    </div>
    <div class="edit-item">
        <span>背景图:</span>
        <el-image :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[edit.user_background]" show-progress :initial-index="0" class="background" :src="edit.user_background"></el-image>
        <el-button
            type="primary"
            size="small"
            @click="bginput.click()"
            >上传</el-button
          >
          <input type="file" accept="image/*" @change="handlebgChange" ref="bginput" style="display: none;" />
    </div>
    <template #footer>
        <span>
          <el-button @click="editshow = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleEditSubmit"
            >确定</el-button
          >
        </span>
      </template>
  </el-dialog>
  <el-dialog v-model="addshow" @close="clearadd" title="编辑" width="300px">
    <div class="add-item">
        <span>邮箱:</span>
        <el-input style="width: 200px;" v-model="add.user_mail"/>
    </div>
    <div class="add-item">
        <span>密码:</span>
        <el-input style="width: 200px;" v-model="add.user_password" show-password/>
    </div>
    <template #footer>
        <span>
          <el-button @click="addshow = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleaddSubmit"
            >确定</el-button
          >
        </span>
      </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {ref,reactive,onBeforeMount} from 'vue'
import { Search,Plus} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {GetUsers,UpdateUser,AddUser,GetUserData} from "@/service/api/user"
import { UploadAvatur,UploadBg } from '@/service/api/image';
import Data from './Data.vue';
let PageNo=ref(1)
let avaturinput=ref(null)
let bginput=ref(null)
let detail=ref({})
let edit=ref({})
let add=ref({
  user_mail:'',
  user_password:'',
})
let avaturfile=null
let bgfile=null
let addshow=ref(false)
let editshow=ref(false)
let detailshow=ref(false)
let PageSize=ref(10)
let total=ref(0)
let searchKeyword=ref('')
let dateRange=ref([])
let tableData=ref([])
let UserData=reactive([
    {
        title:'总用户数',
        num:'0'
    },
    {
        title:'今日新增',
        num:'0'
    },
    {
        title:'活跃用户',
        num:'0'
    },
    {
        title:'网红用户',
        num:'0'
    }
])

onBeforeMount(()=>{
    getusers()
    getuserdata()
})

function getuserdata(){
  GetUserData().then(res=>{
    if(res.data.code==200){
      UserData[0].num=String(res.data.data.alltotal)
      UserData[1].num=String(res.data.data.newtotal)
      UserData[2].num=String(res.data.data.hototal)
      UserData[3].num=String(res.data.data.idoltotal)
    }
  })
}
function handleaddSubmit(){
  console.log(add.value)
  AddUser({
    user_mail:add.value.user_mail,
    user_password:add.value.user_password
  }).then(res=>{
    if(res.data.code==200){
      ElMessage.success('添加成功')
      addshow.value=false
      tableData.value=[]
      PageNo.value=1
      getuserdata()
      getusers()
    }
  })
}
function clearadd(){
  add.value={
    user_mail:'',
    user_password:'',
  }
}
function handleAdd(){
  addshow.value=true
}
async function handleEditSubmit(){
  if(avaturfile){
    let formData = new FormData();
    formData.append('file', avaturfile);
    formData.append('user','admin')
    formData.append('use','avatur')
    formData.append('time',String(Date.now()))
    edit.value.user_avatur=(await UploadAvatur(formData)).data.imgUrl
  }
  if(bgfile){
    let formData = new FormData();
    formData.append('file', bgfile);
    formData.append('user','admin')
    formData.append('use','bg')
    formData.append('time',String(Date.now()))
    edit.value.user_background=(await UploadBg(formData)).data.imgUrl
  }
  UpdateUser({
    user_id:edit.value.user_id,
    user_nickname:edit.value.user_nickname,
    user_avatur:edit.value.user_avatur,
    is_delete:edit.value.is_delete,
    user_background:edit.value.user_background,
  }).then(res=>{
    if(res.data.code==200){
      ElMessage.success('修改成功')
      editshow.value=false
      tableData.value=[]
      PageNo.value=1
      getuserdata()
      getusers()
    }
  })
}
function clearedit(){
    avaturfile=null
    bgfile=null
}
function handleAvaturChange(event){
  avaturfile=event.target.files[0]
  if(!avaturfile.type.startsWith('image/'))return ElMessage.error('请选择正确格式文件')
  const reader = new FileReader();
  reader.onload = (e) => {
    edit.value.user_avatur = e.target.result;
    };
  reader.readAsDataURL(avaturfile);
}

function handlebgChange(event){
  bgfile=event.target.files[0]
  if(! bgfile.type.startsWith('image/'))return ElMessage.error('请选择正确格式文件')
  const reader = new FileReader();
  reader.onload = (e) => {
    edit.value.user_background = e.target.result;
    };
  reader.readAsDataURL( bgfile);
}

function handleEdit(item){
    edit.value=JSON.parse(JSON.stringify(item))
    editshow.value=true
}
function handleView(item){
    detail.value=item
    detailshow.value=true
}
function handleSizeChange(value){
    tableData.value=[]
    PageSize.value=value
    getusers()
}

function handlePageNoChange(value){
    tableData.value=[]
    PageNo.value=value
    getusers()
}
function handleClear(){
    dateRange.value=[]
}
function handleSearch(){
    tableData.value=[]
    PageNo.value=1
    getusers()
}
function getusers(){
    GetUsers({
        PageNo:PageNo.value,
        PageSize:PageSize.value,
        keywords:searchKeyword.value,
        starttime:dateRange.value[0]?new Date(dateRange.value[0]).getTime():null,
        endtime:dateRange.value[1]?new Date(dateRange.value[1]).getTime():null
    }).then(res=>{
        if(res.data.code===200){
            tableData.value=[...tableData.value,...res.data.data.users]
            total.value=res.data.data.total
        }
    })
}

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hours = date.getHours()
  const minutes = date.getMinutes()
  const formattedMonth = month < 10 ? '0' + month : month
  const formattedDay = day < 10 ? '0' + day : day
  const formattedHours = hours < 10 ? '0' + hours : hours
  const formattedMinutes = minutes < 10 ? '0' + minutes : minutes
 
  return `${year}-${formattedMonth}-${formattedDay}`
}

</script>

<style lang="scss" scoped>
@import url("@/assets/css/view.scss");
</style>
